import { useConfirm } from "@/hooks/index"
import { newUserActivityPage,deleteActivity } from '@/api/OperationManage/marketingManagements'
const searchTableRef = ref(null)
const weekDateList = ['周一','周二','周三','周四','周五','周六','周日']



const storeList = ref([])
export const DiscountData = ()=>{
  return {
    searchTableRef,
    weekDateList,
    storeList,
  }
}


// 表单校验
// 表格限购校验
export const discountValidateTable = (row)=>{
  return [{
    required: true,
    validator: (rule, value, callback) => {
      if(!row.discount){
        callback('折扣不可为空或0')
      }else{
       callback()
      }
    },
    message: '折扣不可为空或0',
    trigger: ['blur','change']
  }]
}


export const useCurd = ()=>{
  const router = useRouter()

  //表格数据
  const tableLoading = ref(false)
  const total = ref(0)
  const tableData = ref([])

  // 搜索
  const handlerSearch = async (data) => {
    console.log(data,'data');
    try{
      tableLoading.value = true
      const res = await newUserActivityPage({
        ...data,
        activityType:2,
      })
      tableData.value = res.records
      total.value = res.total
    }finally{
      tableLoading.value = false
    }
  }


  const actionActivity = async (opsType,row) => {
    const text = opsType ? '终止' : '删除'
    ElMessageBox.confirm(`是否${text}【${row.activityName}】活动?`,'提示',{
      type:'warning',
      confirmButtonText:text,
      confirmButtonClass:'el-button--danger',
      beforeClose:async (action,instance,done)=>{
        const func = async ()=>{
          const params = {
            activityId:row.id,
            opsType,
          }
          return await deleteActivity(params)
        }
        const res = await useConfirm(action,instance,done,func)
        if(res){
          ElMessage.success(text+'成功')
          searchTableRef.value.handlerSearch()
        }
      }
    })
  }
  // 表格配置
  const btnLefts = [
    {
      label:'新建活动',
      type:'primary',
      show:()=>true,
      img:new URL("@/assets/icon/btn-add.png",import.meta.url),
      click:()=>{
        router.push({name:'DiscountRestrictionAdd'})
      }
    },
  ]
  const btnRights = []
  const activeState = [
    {
      label:'未开始',
      value:0
    },
    {
      label:'进行中',
      value:1
    },
    {
      label:'已结束',
      value:2
    }
  ]
  const tableForms = ref([
    {
      type: "input",
      prop: 'activityName',
      placeholder: "活动名称",
      label: "",
      model: '',
    },
    {
      type: "select",
      prop: 'activityStatus',
      placeholder: "活动状态",
      filterable:true,
      data:activeState,
      label: "",
      model: '',
    },
    {
      type: "datePicker",
      prop: ["createStartTime", "createEndTime"],
      startPlaceholder: "创建开始时间",
      endPlaceholder: "创建结束时间",
      label: "",
      model: [],
    },
  ])
  const tableConfig = ref([
    {
      type:'slot',
      slotName:"activeName",
      label:'活动名称',
      prop:'name',
      minWidth:200
    },
    {
      label:'活动对象',
      prop:'activityMemberType',
      textOverflow:true,
      minWidth:140,
      format:(value,row)=>{
        if(row.activityMember == 0){
          return `全部会员(${value == 0 ? '全部' : '未消费会员'})`
        }else{
          return `指定会员等级(${row.activityMemberValue.join(',')})`
        }
      }
    },
    {
      textOverflow:true,
      label:'活动门店及业务',
      prop:'businessScope',
      minWidth:130,
      format:(value,row)=>{
        if(value === 0){
          return '全部门店及业务'
        }else{
          return row.activityStoreData.map(item=>item.storeName).filter(Boolean).join('，')
        }
      }
    },
    {
      label:'状态',
      prop:'activityStatus',
      minWidth:140,
      format:(value)=>{
        return activeState.find(item=>item.value === value)?.label || '-'
      }
    },
    {
      label:'活动时间',
      prop:'activityTimeType',
      textOverflow:true,
      minWidth:220,
      format:(value,row)=>{
        if(value === 1){
          return `${row.activityStartTime}-${row.activityEndTime}`
        }
        // return row.typeValue.map(item=>weekDateList[item-1]).join('，')
        return row.activityCycle.join(',')
      }
    },
    {
      label:'创建时间',
      prop:'createTime',
      minWidth:160,
    },
    {
      type:'action',
      label:'操作',
      fixed: "right",
      width:400,
      btns:[
        {
          label:()=>'数据',
          type:'primary',
          show:()=>true,
          click:(row)=>{
            router.push({
              name:'ActivityData',
              query:{
                id:row.id
              } 
            })
          }
        },
        {
          label:()=>'编辑',
          type:'success',
          show:(row)=>{
            return row.activityStatus == 1 ? true : false
          },
          click:(row)=>{
            // console.log('编辑',row)
            router.push({name:'DiscountRestrictionEdit',query:{id:row.id}})
          }
        },
        {
            label:()=>'复制',
            type:'primary',
            show:(row)=>true,
            click:(row)=>{
              console.log('编辑',row)
              router.push({name:'DiscountRestrictionCopy',query:{isCopy:true,isCopyId:row.id}})
            }
          },
        {
          label:()=>'终止',
          type:'danger',
          show:(row)=>{
            return row.activityStatus == 2 ? false : true
          },
          click:(row)=>{
            actionActivity(true, row)
          }
        },
        {
            label:()=>'删除',
            type:'danger',
            show:(row)=>{
              return row.activityStatus == 2 ? true : false
            },
            click:(row)=>{
              actionActivity(false, row)
            }
          },
      ]
    }
  ])

  return {
    tableLoading,
    total,
    tableData,
    btnLefts,
    btnRights,
    tableConfig,
    tableForms,
    handlerSearch,
  }
}

